<template>
  <div class="autumn-container">
    <!-- 面包 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/dashboard' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>账户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <div class="autumn-center">
      <div class="autumn-layout">
        <!-- 机构树 -->
        <div class="autumn-layout-left">
          <div>
            <el-input placeholder="请输入机构名称过滤" v-model="filterText" />
          </div>
          <el-divider />
          <el-scrollbar>
            <el-tree ref="organTreeRef" :node-key="'id'" :data="treeOrgan"
              :props="{ label: 'name', children: 'children' }" :expand-on-click-node="false" :default-expand-all="true"
              :filter-node-method="filterNode" @node-click="clickNode">
            </el-tree>
          </el-scrollbar>
        </div>

        <div class="autumn-layout-main">
          <!-- 搜索栏 -->
          <div class="query-form">
            <autumn-search :modelValue="queryInfo" @search="search">
              <template #default>
                <el-form-item prop="loginName" label="账号">
                  <el-input v-model="queryInfo.loginName" />
                </el-form-item>
                <el-form-item prop="name" label="姓名">
                  <el-input v-model="queryInfo.name" />
                </el-form-item>
                <el-form-item prop="isEnable" label="启用">
                  <el-select v-model="queryInfo.isEnable">
                    <el-option label="是" value="1" />
                    <el-option label="否" value="0" />
                  </el-select>
                </el-form-item>
              </template>
            </autumn-search>
          </div>

          <!-- 数据表格 -->
          <div class="main-body top">
            <autumn-table style="width: 100%;" ref="mainTableRrf" :page="page" @changePage="changePage"
              @changeSelect="changeSelect">
              <template #button>
                <el-button type="primary" icon="el-icon-plus" v-if="$hasPermission('system:account:add')"
                  @click="toView">新增
                </el-button>
                <el-button type="warning" icon="el-icon-refresh" v-if="$hasPermission('system:account:reset-password')"
                  :disabled="selectNum == 0" @click="reset">重置密码
                </el-button>
              </template>
              <template #column>
                <el-table-column type="selection" label="#" fixed="left" align="center" />
                <el-table-column prop="loginName" label="账号" />
                <el-table-column prop="name" label="姓名" />
                <el-table-column label="性别" align="center" width="80">
                  <template #default="scope">
                    <el-tag size="small" type="success" v-if="scope.row.gender == 1">男</el-tag>
                    <el-tag size="small" type="warning" v-else-if="scope.row.gender == 2">女</el-tag>
                    <el-tag size="small" type="info" v-else>其它</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="图像" align="center" width="80">
                  <template #default="scope">
                    <el-avatar :size="'small'" :src="$previewUrl(scope.row.avatar)" />
                  </template>
                </el-table-column>
                <el-table-column prop="organName" label="所属机构" />
                <el-table-column prop="email" label="邮箱" />
                <el-table-column prop="phone" label="联系方式" />
                <el-table-column label="管理员" align="center" width="80">
                  <template #default="scope">
                    <el-tag size="small" :type="scope.row.isAdmin == 1 ? 'success' : 'warning'">{{ scope.row.isAdmin ==
                        1
                        ? '是' : '否'
                    }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="启用" align="center" width="100">
                  <template #default="scope">
                    <el-switch v-model="scope.row.isEnable" :active-value="1" :inactive-value="0"
                      :disabled="!$hasPermission('system:account:enable&system:account:disable')"
                      @change="changeEnabled(scope.row)" />
                  </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" align="center" width="200">
                  <template #default="scope">
                    <el-button-group>
                      <el-button type="info" icon="el-icon-view" size="small" title="查看"
                        @click="toView(scope.row, '1')" />
                      <el-button type="primary" icon="el-icon-edit" size="small" title="编辑"
                        v-if="$hasPermission('system:account:update')" @click="toView(scope.row)" />
                      <el-button type="danger" icon="el-icon-delete" size="small" title="删除"
                        v-if="$hasPermission('system:account:delete')" @click="del(scope.row)" />
                      <el-button type="success" icon="el-icon-coordinate" size="small" title="授权"
                        v-if="$hasPermission('system:account:grant')" @click="toGrant(scope.row)" />
                    </el-button-group>
                  </template>
                </el-table-column>
              </template>
            </autumn-table>
          </div>
        </div>
      </div>
    </div>

    <!-- 角色弹窗 -->
    <el-dialog title="用户授权" v-model="showDialog" width="33%" :close-on-click-modal="false" @close="handleClose">
      <el-transfer v-model="account.roleIds" :data="roles" filterable :titles="['未授权角色', '已授权角色']"
        :props="{ key: 'id', label: 'name' }" />
      <template #footer>
        <div class="dialog-footer" style="margin-top: 10px;text-align: right;">
          <el-button type="primary" @click="grant">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import useTable from 'src/hooks/useTable'
import { $hasPermission, $confirmMsg, $previewUrl } from 'src/hooks/useCommon'
import { pageAccount, enableAccount, disableAccount, deleteAccount, resetPassword, listCheckedRole, grantRole } from 'src/api/system/account'
import { listRole } from 'src/api/system/role'
import { listOrgan } from 'src/api/system/organ'

const { selectNum, page, changeSelect } = useTable()

// 查询角色
const roles = ref<Array<any>>([])
listRole().then(({ data }) => { roles.value = data })

// 查询/监听树形机构
const organTreeRef = ref()
const treeOrgan = ref<Array<any>>([])
listOrgan().then(({ data }) => { treeOrgan.value = data })
const filterText = ref<string>('')
watch(filterText, (newVal) => organTreeRef.value.filter(newVal))
// 过滤/选中树形节点
const filterNode = function (value: any, data: any, node: any) {
  if (!value) return true
  return node.label.indexOf(value) > -1
}
const clickNode = function (data: any, node: any, el: any) {
  queryInfo.organId = data.id
  search()
}

// 分页查询
const queryInfo = reactive({
  organId: '',
  loginName: '',
  name: '',
  isEnable: '',
  gender: ''
})
const changePage = function (pageNumber: number, pageSize: number) {
  page.pageNumber = pageNumber
  page.pageSize = pageSize
  pageAccount({ ...queryInfo, pageNumber, pageSize }).then(({ data }) => {
    page.data = data.list
    page.total = data.total
  })
}
const search = function () {
  changePage(1, 10)
}
search()

// 启/禁用账户
const changeEnabled = function (row: any) {
  const id = row.id
  const isEnable = row.isEnable
  if (isEnable) {
    enableAccount(id).then(() => {
      search()
    })
  } else {
    disableAccount(id).then(() => {
      search()
    })
  }
}

// 删除账户
const del = function (row: any) {
  const ids = [row.id]
  $confirmMsg('确认删除吗？', () => {
    deleteAccount(ids).then(() => {
      search()
    })
  })
}

// 查看账户
const router = useRouter()
const toView = function (row: any, type?: string) {
  const id = row.id
  router.push({
    path: type ? '/system/account/accountView' : '/system/account/accountForm',
    query: { id }
  })
}

// 角色授权
const showDialog = ref<boolean>(false)
const account = reactive({
  id: '',
  roleIds: []
})
const toGrant = function (row: any) {
  account.id = row.id
  listCheckedRole(account.id).then(({ data }) => {
    account.roleIds = data
  })
  showDialog.value = true
}
const grant = function () {
  grantRole(account).then(() => {
    showDialog.value = false
  })
}
const handleClose = function () {
  account.id = ''
  account.roleIds = []
}

// 重置密码
const mainTableRrf = ref()
const reset = function () {
  const selection = mainTableRrf.value.$refs.dataTableRef.getSelectionRows()
  const ids: Array<string> = []
  selection.forEach((item: any) => {
    ids.push(item.id)
  })
  $confirmMsg('确认重置密码吗？', () => {
    resetPassword(ids).then(() => {
      search()
    })
  })
}

</script>

<style lang="scss" scoped>
:deep(.el-transfer-panel__header) {
  padding-top: 10px;

  .el-checkbox {
    .el-checkbox__label {
      font-size: 14px;
    }
  }
}

:deep(.el-transfer-panel__filter.el-input) {
  width: 80%;

  .el-input__inner {
    height: 28px;
  }
}
.el-divider {
  margin: 10px 0;
}
</style>
